package com.krtech.wecard.module.weixin.handler;

import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.module.sys.entity.SysUser;
import com.krtech.wecard.module.sys.service.LoginService;
import com.krtech.wecard.module.sys.service.SysUserService;
import com.krtech.wecard.module.weixin.bean.WxOpenIdManage;
import com.krtech.wecard.module.weixin.builder.TextBuilder;
import com.krtech.wecard.module.weixin.service.WxOpenIdManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Component
public class SubscribeHandler extends AbstractHandler {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private WxOpenIdManageService wxOpenIdManageService;

    @Autowired
    private LoginService loginService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

        // 获取微信用户基本信息
        try {
//            WxMpUser userWxInfo = weixinService.getUserService()
//                    .userInfo(wxMessage.getFromUser(), null);
//            if (userWxInfo != null) {
//                // TODO 可以添加关注用户到本地数据库
//                SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.COL_PUBLIC_OPEN_ID, userWxInfo.getOpenId()));
//                if (user == null){
//                    return null;
//                }
//                user.setHasFocusPublicNumber(1);
//                sysUserService.updateById(user);
//            }
            SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.COL_PUBLIC_OPEN_ID, wxMessage.getFromUser()));
            if (user == null){
                return null;
            }
            user.setHasFocusPublicNumber(1);
            sysUserService.updateById(user);

            // 存放公众号openId以及是否关注的状态
            WxOpenIdManage wxOpenIdManage = loginService.getOpenIdManageInfoByPublicOpenId(wxMessage.getFromUser());
            wxOpenIdManage.setHasFocusPublicNumber(1);
            wxOpenIdManage.setUpdatedTime(new Date());
            wxOpenIdManageService.updateById(wxOpenIdManage);
        }
//        catch (WxErrorException e) {
//            if (e.getError().getErrorCode() == 48001) {
//                this.logger.info("该公众号没有获取用户信息权限！");
//            }
//        }
        catch (Exception e) {
            e.printStackTrace();
        }


        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
            return new TextBuilder().build("感谢关注", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
            throws Exception {
        //TODO
        return null;
    }
}
